import { NextRequest, NextResponse } from 'next/server';
import { auth } from '../../../../auth';
import { prisma, dbOperation } from '@/lib/db';
import { Project, ProjectUser } from '@prisma/client';

// 扩展项目类型以包含状态字段
interface ProjectWithStatus extends Project {
  status?: string;
}

type ProjectUserWithUser = ProjectUser & {
  user: {
    id: string;
    name: string | null;
    email: string | null;
    image: string | null;
  };
};

type ProjectWithUsers = ProjectWithStatus & {
  users: ProjectUserWithUser[];
  tasks?: any[];
  _count?: {
    tasks: number;
    comments?: number;
    users?: number;
  };
};

// 创建示例项目，如果数据库中没有项目
async function createExampleProjectIfNeeded(userId: string): Promise<void> {
  try {
    // 检查用户是否已有项目
    const userProjectCount = await prisma.projectUser.count({
      where: { userId }
    });

    if (userProjectCount === 0) {
      console.log("[API] 用户没有项目，创建示例项目");

      // 创建示例项目
      await prisma.project.create({
        data: {
          name: '欢迎使用项目管理系统',
          description: '这是一个示例项目，帮助您快速上手。您可以添加任务、邀请团队成员，并跟踪项目进度。',
          users: {
            create: {
              userId: userId,
              role: 'OWNER'
            }
          },
          tasks: {
            create: [
              {
                title: '完善项目描述',
                description: '添加更多项目细节，明确目标和时间线',
                status: 'TODO',
                priority: 'HIGH',
                assigneeId: userId
              },
              {
                title: '邀请团队成员',
                description: '邀请同事或合作伙伴加入项目协作',
                status: 'TODO',
                priority: 'MEDIUM'
              }
            ]
          }
        }
      });

      console.log("[API] 示例项目创建成功");
    }
  } catch (error) {
    console.error("[API] 创建示例项目失败:", error);
    // 不抛出错误，让正常流程继续
  }
}

// 获取项目列表或单个项目
export async function GET(request: NextRequest) {
  try {
    console.log("[API] GET /api/project 请求开始处理");
    
    // 检查用户是否已认证
    const session = await auth();
    console.log("[API] 用户认证状态:", session ? "已认证" : "未认证", "用户ID:", session?.user?.id || "无");

    if (!session?.user) {
      console.log("[API] 用户未认证，返回401");
      return NextResponse.json(
        { success: false, message: '未授权访问' },
        { status: 401 }
      );
    }

    // 确保用户至少有一个项目
    await createExampleProjectIfNeeded(session.user.id);
    
    // 获取查询参数
    const searchParams = request.nextUrl.searchParams;
    const projectId = searchParams.get('id');
    console.log("[API] 请求参数:", { projectId });

    // 如果提供了项目ID，返回单个项目
    if (projectId) {
      console.log("[API] 获取单个项目:", projectId);
      
      const project = await dbOperation(async () => {
        return prisma.project.findFirst({
          where: {
            id: projectId,
            users: {
              some: {
                userId: session.user.id,
              },
            },
          },
          include: {
            users: {
              include: {
                user: {
                  select: {
                    id: true,
                    name: true,
                    email: true,
                    image: true,
                  },
                },
              },
            },
            tasks: {
              orderBy: {
                updatedAt: 'desc',
              },
              take: 10,
              select: {
                id: true,
                title: true,
                status: true,
                priority: true,
                dueDate: true,
                updatedAt: true,
                assignee: {
                  select: {
                    id: true,
                    name: true,
                    image: true,
                  },
                },
              },
            },
            _count: {
              select: {
                tasks: true,
                comments: true,
              },
            },
          },
        });
      });

      console.log("[API] 项目查询结果:", { success: project.success, projectExists: !!project.data });

      if (!project.success) {
        console.log("[API] 数据库操作失败:", project.error);
        return NextResponse.json(
          { success: false, message: '获取项目失败', error: project.error },
          { status: 500 }
        );
      }

      if (!project.data) {
        console.log("[API] 项目不存在或无权访问");
        return NextResponse.json(
          { success: false, message: '项目不存在或您无权访问' },
          { status: 404 }
        );
      }

      // 格式化项目成员，简化返回结构
      const formattedProject = {
        ...project.data,
        members: project.data.users.map((userProject: any) => ({
          ...userProject.user,
          role: userProject.role,
          joinedAt: userProject.joinedAt,
        })),
        status: 'planning', // 设置默认状态
        users: undefined, // 移除原始users字段
      };

      console.log("[API] 返回格式化的单个项目数据");
      return NextResponse.json({ success: true, data: formattedProject }, {
        headers: {
          'Cache-Control': 'no-store, must-revalidate, max-age=0',
          'Pragma': 'no-cache'
        }
      });
    }

    // 获取用户参与的所有项目
    console.log("[API] 获取用户参与的所有项目, 用户ID:", session.user.id);
    
    const userProjects = await dbOperation(async () => {
      return prisma.project.findMany({
        where: {
          users: {
            some: {
              userId: session.user.id,
            },
          },
        },
        orderBy: {
          updatedAt: 'desc',
        },
        include: {
          users: {
            where: {
              role: 'OWNER',
            },
            include: {
              user: {
                select: {
                  id: true,
                  name: true,
                  image: true,
                },
              },
            },
          },
          _count: {
            select: {
              tasks: true,
              users: true,
            },
          },
        },
      });
    });

    console.log("[API] 用户项目查询结果:", { 
      success: userProjects.success, 
      projectCount: userProjects.data ? userProjects.data.length : 0 
    });

    if (!userProjects.success || !userProjects.data) {
      console.log("[API] 数据库操作失败:", userProjects.error);
      return NextResponse.json(
        { success: false, message: '获取项目列表失败', error: userProjects.error },
        { status: 500 }
      );
    }

    // 格式化返回数据
    const formattedProjects = userProjects.data.map((project: any) => {
      // 检查是否有owner用户
      const owner = project.users.length > 0 ? project.users[0].user : null;
      
      return {
        ...project,
        owner,
        memberCount: project._count?.users || 1,
        taskCount: project._count?.tasks || 0,
        status: 'planning', // 设置默认状态
        users: undefined, // 移除原始users字段
      };
    });

    console.log("[API] 返回格式化的项目列表数据, 项目数量:", formattedProjects.length);
    return NextResponse.json(
      { success: true, data: formattedProjects },
      {
        headers: {
          'Cache-Control': 'no-store, must-revalidate, max-age=0',
          'Pragma': 'no-cache'
        }
      }
    );
  } catch (error: any) {
    console.error('[API] 获取项目失败:', error);
    return NextResponse.json(
      { success: false, message: '获取项目失败', error: error.message },
      { status: 500 }
    );
  }
}

// 创建新项目
export async function POST(request: NextRequest) {
  try {
    // 检查用户是否已认证
    const session = await auth();

    if (!session?.user) {
      return NextResponse.json(
        { success: false, message: '未授权访问' },
        { status: 401 }
      );
    }

    // 解析请求体
    const body = await request.json();

    // 验证必填字段
    if (!body.name) {
      return NextResponse.json(
        { success: false, message: '项目名称为必填项' },
        { status: 400 }
      );
    }

    // 创建新项目
    const result = await dbOperation(async () => {
      return prisma.project.create({
        data: {
          name: body.name,
          description: body.description || '',
          users: {
            create: {
              userId: session.user.id,
              role: 'OWNER',
            },
          },
        },
        include: {
          users: {
            include: {
              user: {
                select: {
                  id: true,
                  name: true,
                  email: true,
                  image: true,
                },
              },
            },
          },
        },
      });
    });

    if (!result.success) {
      return NextResponse.json(
        { success: false, message: '创建项目失败', error: result.error },
        { status: 500 }
      );
    }

    // 格式化项目成员
    const formattedProject = {
      ...result.data,
      members: result.data.users.map((userProject: ProjectUserWithUser) => ({
        ...userProject.user,
        role: userProject.role,
        joinedAt: userProject.joinedAt,
      })),
      users: undefined, // 移除原始users字段
    };

    return NextResponse.json(
      { success: true, message: '项目创建成功', data: formattedProject },
      { status: 201 }
    );
  } catch (error: any) {
    console.error('创建项目失败:', error);
    return NextResponse.json(
      { success: false, message: '创建项目失败', error: error.message },
      { status: 500 }
    );
  }
}

// 更新项目
export async function PUT(request: NextRequest) {
  try {
    // 检查用户是否已认证
    const session = await auth();

    if (!session?.user) {
      return NextResponse.json(
        { success: false, message: '未授权访问' },
        { status: 401 }
      );
    }

    // 获取查询参数
    const searchParams = request.nextUrl.searchParams;
    const projectId = searchParams.get('id');

    if (!projectId) {
      return NextResponse.json(
        { success: false, message: '未提供项目ID' },
        { status: 400 }
      );
    }

    // 验证用户是否有权限更新项目
    const userProjectRole = await dbOperation(async () => {
      return prisma.projectUser.findFirst({
        where: {
          projectId,
          userId: session.user.id,
          role: {
            in: ['OWNER', 'ADMIN'], // 只有所有者和管理员可以更新项目
          },
        },
      });
    });

    if (!userProjectRole.success || !userProjectRole.data) {
      return NextResponse.json(
        { success: false, message: '您无权更新此项目' },
        { status: 403 }
      );
    }

    // 解析请求体
    const body = await request.json();

    // 只允许更新特定字段
    const allowedFields = ['name', 'description'];
    const updateData: Record<string, any> = {};

    Object.keys(body).forEach(key => {
      if (allowedFields.includes(key)) {
        updateData[key] = body[key];
      }
    });

    // 如果没有有效的字段需要更新，返回错误
    if (Object.keys(updateData).length === 0) {
      return NextResponse.json(
        { success: false, message: '没有提供有效的更新字段' },
        { status: 400 }
      );
    }

    // 更新项目
    const result = await dbOperation(async () => {
      return prisma.project.update({
        where: { id: projectId },
        data: updateData,
        include: {
          users: {
            include: {
              user: {
                select: {
                  id: true,
                  name: true,
                  email: true,
                  image: true,
                },
              },
            },
          },
        },
      });
    });

    if (!result.success) {
      return NextResponse.json(
        { success: false, message: '更新项目失败', error: result.error },
        { status: 500 }
      );
    }

    // 格式化项目成员
    const formattedProject = {
      ...result.data,
      members: result.data.users.map((userProject: ProjectUserWithUser) => ({
        ...userProject.user,
        role: userProject.role,
        joinedAt: userProject.joinedAt,
      })),
      users: undefined, // 移除原始users字段
    };

    return NextResponse.json({
      success: true,
      message: '项目更新成功',
      data: formattedProject,
    });
  } catch (error: any) {
    console.error('更新项目失败:', error);
    return NextResponse.json(
      { success: false, message: '更新项目失败', error: error.message },
      { status: 500 }
    );
  }
}

// 删除项目
export async function DELETE(request: NextRequest) {
  try {
    // 检查用户是否已认证
    const session = await auth();

    if (!session?.user) {
      return NextResponse.json(
        { success: false, message: '未授权访问' },
        { status: 401 }
      );
    }

    // 获取查询参数
    const searchParams = request.nextUrl.searchParams;
    const projectId = searchParams.get('id');

    if (!projectId) {
      return NextResponse.json(
        { success: false, message: '未提供项目ID' },
        { status: 400 }
      );
    }

    // 验证用户是否为项目所有者
    const userProjectRole = await dbOperation(async () => {
      return prisma.projectUser.findFirst({
        where: {
          projectId,
          userId: session.user.id,
          role: 'OWNER', // 只有所有者可以删除项目
        },
      });
    });

    if (!userProjectRole.success || !userProjectRole.data) {
      return NextResponse.json(
        { success: false, message: '只有项目所有者可以删除项目' },
        { status: 403 }
      );
    }

    // 删除项目（Prisma级联删除将处理关联数据）
    const result = await dbOperation(async () => {
      return prisma.project.delete({
        where: { id: projectId },
      });
    });

    if (!result.success) {
      return NextResponse.json(
        { success: false, message: '删除项目失败', error: result.error },
        { status: 500 }
      );
    }

    return NextResponse.json({ success: true, message: '项目删除成功' });
  } catch (error: any) {
    console.error('删除项目失败:', error);
    return NextResponse.json(
      { success: false, message: '删除项目失败', error: error.message },
      { status: 500 }
    );
  }
} 